package commons.base.nio;

import java.io.IOException;
import java.nio.channels.spi.SelectorProvider;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class IOWorkerGroup implements AutoCloseable{

	private List<IOWorker> workers = new ArrayList<>();
	private ExecutorService executorService;
	private AtomicInteger seq = new AtomicInteger(0);
	
	public IOWorkerGroup(SelectorProvider selectorProvider) throws IOException{
		int num = Runtime.getRuntime().availableProcessors() * 2;
		executorService = Executors.newFixedThreadPool(num);
		
		for(int i=0; i<num; i++){
			IOWorker worker = new IOWorker(selectorProvider);
			workers.add(worker);
			executorService.submit(worker);
		}
	}
	
	public IOWorker chooseWorker(){
		int index = Math.abs(seq.getAndIncrement()) % workers.size();
		
		return workers.get(index);
	}
	
	@Override
	public void close() throws Exception {
		workers.forEach(w -> {
			try {
				w.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		});
		
		executorService.shutdown();
	}
}
